// #define _XOPEN_SOURCE  1
// #define _XOPEN_SOURCE_EXTENDED 1
// #define _SVID_SOURCE  1
// #define _POSIX_SOURCE  1
// #define _BSD_SOURCE  1
#include <header.h>
#include "utils.h"
#include "request.h"
#include "receive.h"
#include "tire.h"
#include "entity.h"
#define BUFF_SIZE 1024


unsigned short command;// 命令,这个变量要设置为全局，因为处理命令要用
char parameter[BUFF_SIZE];// 全局,用户输入内容

int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);

	// 从配置文件中加载服务器ip
	char *ip = getIpFromConfig();
	// 从配置文件中加载服务器端口
	char *port = getPortFromConfig();

	int net_fd = socket(AF_INET, SOCK_STREAM, 0);

	struct sockaddr_in client_addr;
	client_addr.sin_family = AF_INET;
	client_addr.sin_port = htons(atoi(port));
	client_addr.sin_addr.s_addr = inet_addr(ip);

	int res_connect = connect(net_fd, (struct sockaddr*)&client_addr, sizeof(client_addr));
	ERROR_CHECK(res_connect,-1,"res_connect");

	int epoll_fd = epoll_create(1);
	addEpoll(epoll_fd, net_fd);
	addEpoll(epoll_fd, STDIN_FILENO);


	// 初始化tire树
	initTire();

	
	while(1){
		struct epoll_event list[5];
		int epoll_num = epoll_wait(epoll_fd, list, 5, -1);

		for (int i = 0; i < epoll_num; i++){
			
			if(list->data.fd == net_fd){
				// 服务端有数据到来

				// 接收服务器返回的是成功还是失败
				int ret = receiveFlag(net_fd);


				
				if(ret == 0){
					// 失败
					// printf 具体内容
					handleError(command);

				}else{
					// printf("服务器成功收到请求命令！\n");
					// 处理对应请求，既发送文件还是接收文件
					resolve(net_fd, command, parameter);
				}

				
			}else if(list[i].data.fd == STDIN_FILENO){
				// 客户端输入
				memset(parameter, 0, sizeof(parameter));

				// 只读取一行
				fgets(parameter, sizeof parameter, stdin);
				// TODO 解析命令
				int ret = handleCommand(&command, parameter);

				if(ret == 0){
					// 非法命令
					printf("非法命令\n");
				}else{
					request(net_fd, command, parameter);
				}
			}
		}
	}

	close(net_fd);
	free(ip);
	free(port);
	return 0;
}
